package game;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.RandomAccessFile;
import javax.swing.JOptionPane;
import rps.RPSClient;

public class configuracion extends JFrameConFondo {

	public configuracion() {
		initComponents();
	}

	private void initComponents() {

		jButton1 = new javax.swing.JButton();
		jButton2 = new javax.swing.JButton();
		jButton3 = new javax.swing.JButton();
		jPanel1 = new javax.swing.JPanel();
		jLabel1 = new javax.swing.JLabel();
		jTextField1 = new javax.swing.JTextField();
		jLabel2 = new javax.swing.JLabel();
		jButton4 = new javax.swing.JButton();
		jTextField2 = new javax.swing.JTextField();
		jButton5 = new javax.swing.JButton();
		jLabel4 = new javax.swing.JLabel();

		setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
		setTitle("Bowling Net");
		setResizable(false);

		jButton1.setIcon(new javax.swing.ImageIcon(getClass().getResource(
				"imagenes/b1.png"))); // NOI18N
		jButton1.setBorder(null);
		jButton1.setBorderPainted(false);
		jButton1.setContentAreaFilled(false);
		jButton1.setPressedIcon(new javax.swing.ImageIcon(getClass()
				.getResource("imagenes/b1_3.png"))); // NOI18N
		jButton1.setRolloverIcon(new javax.swing.ImageIcon(getClass()
				.getResource("imagenes/b1_2.png")));

		jButton2.setIcon(new javax.swing.ImageIcon(getClass().getResource(
				"imagenes/b2.png"))); // NOI18N
		jButton2.setBorder(null);
		jButton2.setContentAreaFilled(false);
		jButton2.setPressedIcon(new javax.swing.ImageIcon(getClass()
				.getResource("imagenes/b2_3.png"))); // NOI18N
		jButton2.setRolloverIcon(new javax.swing.ImageIcon(getClass()
				.getResource("imagenes/b2_2.png"))); // NOI18N

		jButton3.setIcon(new javax.swing.ImageIcon(getClass().getResource(
				"imagenes/b3.png"))); // NOI18N
		jButton3.setBorder(null);
		jButton3.setContentAreaFilled(false);
		jButton3.setPressedIcon(new javax.swing.ImageIcon(getClass()
				.getResource("imagenes/b3_3.png"))); // NOI18N
		jButton3.setRolloverIcon(new javax.swing.ImageIcon(getClass()
				.getResource("imagenes/b3_2.png"))); // NOI18N

		jPanel1.setOpaque(false);

		jLabel1.setIcon(new javax.swing.ImageIcon(getClass().getResource(
				"imagenes/ip.png"))); // NOI18N

		jTextField1.addActionListener(new java.awt.event.ActionListener() {
			public void actionPerformed(java.awt.event.ActionEvent evt) {
				jTextField1ActionPerformed(evt);
			}
		});

		jLabel2.setIcon(new javax.swing.ImageIcon(getClass().getResource(
				"imagenes/b7.png"))); // NOI18N

		jButton4.setIcon(new javax.swing.ImageIcon(getClass().getResource(
				"imagenes/b4.png"))); // NOI18N
		jButton4.setBorder(null);
		jButton4.setBorderPainted(false);
		jButton4.setContentAreaFilled(false);
		jButton4.setPressedIcon(new javax.swing.ImageIcon(getClass()
				.getResource("imagenes/b4_1.png"))); // NOI18N
		jButton4.setRolloverIcon(new javax.swing.ImageIcon(getClass()
				.getResource("imagenes/b4_2.png"))); // NOI18N

		jButton5.setIcon(new javax.swing.ImageIcon(getClass().getResource(
				"imagenes/b6.png"))); // NOI18N
		jButton5.setBorder(null);
		jButton5.setBorderPainted(false);
		jButton5.setContentAreaFilled(false);
		jButton5.setPressedIcon(new javax.swing.ImageIcon(getClass()
				.getResource("imagenes/b6_2.png"))); // NOI18N
		jButton5.setRolloverIcon(new javax.swing.ImageIcon(getClass()
				.getResource("imagenes/b6_3.png")));
		jButton5.addActionListener(new java.awt.event.ActionListener() {
			public void actionPerformed(java.awt.event.ActionEvent evt) {
				jButton5ActionPerformed(evt);
			}
		});

		jLabel4.setIcon(new javax.swing.ImageIcon(getClass().getResource(
				"imagenes/conection.png"))); // NOI18N
		jLabel4.setFocusCycleRoot(true);
		jLabel4.setFocusable(false);
		jLabel4.setInheritsPopupMenu(false);
		jLabel4.setRequestFocusEnabled(false);
		jLabel4.setVerifyInputWhenFocusTarget(false);

		javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(
				jPanel1);
		jPanel1.setLayout(jPanel1Layout);
		jPanel1Layout.setHorizontalGroup(jPanel1Layout.createParallelGroup(
				javax.swing.GroupLayout.Alignment.LEADING).addGroup(
				jPanel1Layout.createSequentialGroup().addGap(40, 40, 40)
						.addComponent(jLabel1).addGap(18, 18, 18).addComponent(
								jTextField1,
								javax.swing.GroupLayout.DEFAULT_SIZE, 102,
								Short.MAX_VALUE).addGap(37, 37, 37)
						.addComponent(jLabel2).addGap(18, 18, 18).addComponent(
								jTextField2,
								javax.swing.GroupLayout.PREFERRED_SIZE, 58,
								javax.swing.GroupLayout.PREFERRED_SIZE).addGap(
								49, 49, 49).addComponent(jButton5).addGap(793,
								793, 793)).addGroup(
				jPanel1Layout.createSequentialGroup().addGap(126, 126, 126)
						.addComponent(jLabel4,
								javax.swing.GroupLayout.PREFERRED_SIZE, 293,
								javax.swing.GroupLayout.PREFERRED_SIZE)
						.addContainerGap(877, Short.MAX_VALUE)).addGroup(
				jPanel1Layout.createSequentialGroup().addGap(216, 216, 216)
						.addComponent(jButton4).addContainerGap(959,
								Short.MAX_VALUE)));
		jPanel1Layout
				.setVerticalGroup(jPanel1Layout
						.createParallelGroup(
								javax.swing.GroupLayout.Alignment.LEADING)
						.addGroup(
								jPanel1Layout
										.createSequentialGroup()
										.addGap(111, 111, 111)
										.addGroup(
												jPanel1Layout
														.createParallelGroup(
																javax.swing.GroupLayout.Alignment.LEADING)
														.addComponent(jLabel1)
														.addComponent(
																jTextField1,
																javax.swing.GroupLayout.PREFERRED_SIZE,
																javax.swing.GroupLayout.DEFAULT_SIZE,
																javax.swing.GroupLayout.PREFERRED_SIZE)
														.addGroup(
																jPanel1Layout
																		.createSequentialGroup()
																		.addGap(
																				2,
																				2,
																				2)
																		.addGroup(
																				jPanel1Layout
																						.createParallelGroup(
																								javax.swing.GroupLayout.Alignment.LEADING)
																						.addComponent(
																								jTextField2,
																								javax.swing.GroupLayout.PREFERRED_SIZE,
																								javax.swing.GroupLayout.DEFAULT_SIZE,
																								javax.swing.GroupLayout.PREFERRED_SIZE)
																						.addComponent(
																								jLabel2)
																						.addComponent(
																								jButton5))))
										.addGap(27, 27, 27)
										.addComponent(
												jLabel4,
												javax.swing.GroupLayout.PREFERRED_SIZE,
												280,
												javax.swing.GroupLayout.PREFERRED_SIZE)
										.addPreferredGap(
												javax.swing.LayoutStyle.ComponentPlacement.RELATED)
										.addComponent(jButton4)
										.addContainerGap(72, Short.MAX_VALUE)));

		jButton4.addActionListener(new java.awt.event.ActionListener() {
			public void actionPerformed(java.awt.event.ActionEvent evt) {
				jButton4ActionPerformed(evt);
			}
		});

		javax.swing.GroupLayout layout = new javax.swing.GroupLayout(
				getContentPane());
		getContentPane().setLayout(layout);
		layout.setHorizontalGroup(layout.createParallelGroup(
				javax.swing.GroupLayout.Alignment.LEADING).addGroup(
				layout.createSequentialGroup().addGap(26, 26, 26).addGroup(
						layout.createParallelGroup(
								javax.swing.GroupLayout.Alignment.LEADING)
								.addComponent(jButton2).addComponent(jButton1)
								//.addComponent(jButton3)
								).addGap(42, 42, 42)
						.addComponent(jPanel1,
								javax.swing.GroupLayout.PREFERRED_SIZE,
								javax.swing.GroupLayout.DEFAULT_SIZE,
								javax.swing.GroupLayout.PREFERRED_SIZE)
						.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE,
								Short.MAX_VALUE)));
		layout
				.setVerticalGroup(layout
						.createParallelGroup(
								javax.swing.GroupLayout.Alignment.LEADING)
						.addGroup(
								javax.swing.GroupLayout.Alignment.TRAILING,
								layout
										.createSequentialGroup()
										.addContainerGap(
												javax.swing.GroupLayout.DEFAULT_SIZE,
												Short.MAX_VALUE)
										.addGroup(
												layout
														.createParallelGroup(
																javax.swing.GroupLayout.Alignment.TRAILING)
														.addComponent(
																jPanel1,
																javax.swing.GroupLayout.PREFERRED_SIZE,
																javax.swing.GroupLayout.DEFAULT_SIZE,
																javax.swing.GroupLayout.PREFERRED_SIZE)
														.addGroup(
																layout
																		.createSequentialGroup()
																		.addComponent(
																				jButton1,
																				javax.swing.GroupLayout.PREFERRED_SIZE,
																				13,
																				javax.swing.GroupLayout.PREFERRED_SIZE)
																		.addPreferredGap(
																				javax.swing.LayoutStyle.ComponentPlacement.RELATED)
																		.addComponent(
																				jButton2,
																				javax.swing.GroupLayout.PREFERRED_SIZE,
																				15,
																				javax.swing.GroupLayout.PREFERRED_SIZE)
																		.addPreferredGap(
																				javax.swing.LayoutStyle.ComponentPlacement.RELATED)
																		//.addComponent(
																			//	jButton3,
																				//javax.swing.GroupLayout.PREFERRED_SIZE,
																				//15,
																				//javax.swing.GroupLayout.PREFERRED_SIZE)
																		.addGap(
																				53,
																				53,
																				53)))
										.addGap(83, 83, 83)));

		jButton1.addActionListener(new java.awt.event.ActionListener() {
			public void actionPerformed(java.awt.event.ActionEvent evt) {
				jButton1ActionPerformed(evt);
			}
		});
		jButton2.addActionListener(new java.awt.event.ActionListener() {
			public void actionPerformed(java.awt.event.ActionEvent evt) {
				jButton2ActionPerformed(evt);
			}
		});
		jButton3.addActionListener(new java.awt.event.ActionListener() {
			public void actionPerformed(java.awt.event.ActionEvent evt) {
				jButton3ActionPerformed(evt);
			}
		});

		java.awt.Dimension screenSize = java.awt.Toolkit.getDefaultToolkit()
				.getScreenSize();
		setBounds((screenSize.width - 800) / 2, (screenSize.height - 600) / 2,
				800, 600);
	}

	private void jButton6ActionPerformed(java.awt.event.ActionEvent evt) {
		JOptionPane.showInputDialog("hola");
	}

	static void configurarServidor() {
		java.awt.EventQueue.invokeLater(new Runnable() {
			public void run() {
				JFrameConFondo jf = new configuracion();
				jf.setImagen("imagenes/configuracion.png");
				jf.setVisible(true);
				leerArchivo();
			}
		});

	}

	public static void leerArchivo() {
		File archivo = null;
		FileReader fr = null;
		BufferedReader br = null;
		String nombreArchivo = "/configurarServer.txt";
		String path = "";
		try {
			path=System.getProperty("user.home").replaceAll("%20", " ");
			path+="/bowling";
			// Apertura del fichero y creacion de BufferedReader para poder
			// hacer una lectura comoda (disponer del metodo readLine()).
			System.out.print(" path: "+path);
			archivo = new File(path + System.getProperty("file.separator")
					+ nombreArchivo);
			fr = new FileReader(archivo);
			br = new BufferedReader(fr);

			// Lectura del fichero
			String linea;
			int i = 0;
			while ((linea = br.readLine()) != null) {
				conexionServidor[i] = linea;
				i++;
			}
			jTextField1.setText(conexionServidor[0]);
			jTextField2.setText(conexionServidor[1]);
		} catch (Exception e) {
			System.out.print("problema leyendo archivo de configuracion.");
		} finally {
			// En el finally cerramos el fichero, para asegurarnos
			// que se cierra tanto si todo va bien como si salta
			// una excepcion.
			try {
				if (null != fr) {
					fr.close();
				}
			} catch (Exception e2) {
				e2.printStackTrace();
			}
		}
	}

	private javax.swing.JButton jButton1;

	private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
		p = new personajes();
		this.dispose();
		p.seleccionPersonaje();
	}

	static personajes p;
	private javax.swing.JButton jButton2;

	private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {
		i = new instrucciones();
		this.dispose();
		i.mostrarInstrucciones();
	}

	instrucciones i;
	private javax.swing.JButton jButton3;
	static String[] conexionServidor = new String[2];

	private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {
		r = new records();
		this.dispose();
		//r.mostrarRecords();
	}

	records r;
	private javax.swing.JButton jButton4;

	private void jButton4ActionPerformed(java.awt.event.ActionEvent evt) {
		String nombreArchivo = "/configurarServer.txt";
		String baseClass = "configuracion";
		String path = "";
		path=System.getProperty("user.home").replaceAll("%20", " ");
		path+="/bowling";
		if (existeArchivoRutaCompelta(path
				+ System.getProperty("file.separator") + nombreArchivo))
			System.out.println("se encontro archivo");
		else
			System.out.println("No se encontro archivo");

		if (guardarArchivo(nombreArchivo, path))
			JOptionPane.showMessageDialog(null, "El archivo fue almacenado");
		else
			System.out.println("No se guardo archivo");

	}

	public static boolean guardarArchivo(String name, String filePath) {
		try {
			// capturamos el nombre original del archivo
			String nametmp = name;
			boolean existe = false;
			// Creamos un archivo con la ruta por defecto y el nombre del
			// archivo original
			File arcd = new File(filePath);
			if (!arcd.exists())
				arcd.mkdirs();

			File arc = new File(arcd.getAbsolutePath()
					+ System.getProperty("file.separator") + name);

			// lo guardamos en el dico duro con permisos de escritura y lectura
			RandomAccessFile raf = new RandomAccessFile(arc, "rw");
			// raf.write(archivo.getFileData());
			// se crea otro archivo igual al primero, con la ruta y nombre
			// iguales,
			// esto a fin de poder compararlo y cambiarle el nombre
			File arc2 = new File(arcd.getAbsolutePath()
					+ System.getProperty("file.separator") + nametmp);
			// se crea el archivo con el nombre que le deseamos poner
			File arc3 = new File(arcd.getAbsolutePath()
					+ System.getProperty("file.separator") + name);
			// pregunta si el cambio de nombre tuvo exito
			boolean correcto = arc2.renameTo(arc3);

			// almacena el archivo con el nuevo nombre
			raf = new RandomAccessFile(arc2, "rw");
			// se borra el archivo con el nombre original del DD
			arc.delete();
			// raf.write(archivo.getFileData());
			if (arc3.exists())
				existe = true;

			System.out.println("texto1: " + jTextField1.getText());
			System.out.println("texto2: " + jTextField2.getText());
			BufferedWriter bw = new BufferedWriter(new FileWriter(arc3));
			bw.write(jTextField1.getText() + "\n" + jTextField2.getText());
			bw.close();
			if (existe)
				return true;
		} catch (IOException e) {
			e.printStackTrace();
		}
		return false;
	}

	public static boolean existeArchivoRutaCompelta(String rutaCompleta) {
		try {
			if (rutaCompleta != null && !rutaCompleta.equals("null")
					&& !rutaCompleta.equals("")) {
				File arc = new File(rutaCompleta);
				if (arc.exists()) {
					if (arc.delete())
						return true;
					else
						return false;
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return false;
	}

	private javax.swing.JButton jButton5;

	private void jButton5ActionPerformed(java.awt.event.ActionEvent evt) {
		RPSClient gc = new RPSClient();
		try {
			if (!jTextField2.getText().isEmpty()) {
				int valorEntero = Integer.parseInt(jTextField2.getText());
				System.out.print("valor: " + valorEntero);
			}
			if (jTextField1.getText().isEmpty()
					|| jTextField2.getText().isEmpty())
				JOptionPane.showMessageDialog(null,
						"Debe indicar la Ip del servidor y el Puerto");
			else {
				if (gc.testConect(jTextField1.getText(), Integer
						.parseInt(jTextField2.getText())))
					JOptionPane.showMessageDialog(null,
							"Conexion Satisfactoria");
				else
					JOptionPane.showMessageDialog(null,
							"Favor verificar la Ip y el Puerto del Servidor");
			}
		} catch (Exception e) {
			JOptionPane.showMessageDialog(null,
					"El valor del Puerto debe ser un valor entero");
		}
	}

	private javax.swing.JLabel jLabel1;
	private javax.swing.JLabel jLabel2;
	private javax.swing.JLabel jLabel4;
	private javax.swing.JPanel jPanel1;
	private static javax.swing.JTextField jTextField1;

	private void jTextField1ActionPerformed(java.awt.event.ActionEvent evt) {

	}

	private static javax.swing.JTextField jTextField2;
}
